package com.example.guava.ratelimiter.test;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.RemovalListener;
import com.google.common.cache.RemovalListeners;
import com.google.common.util.concurrent.RateLimiter;
import lombok.extern.slf4j.Slf4j;

/**
 * Guava缓存
 * @author zhouxuan
 * @date 2020/6/11 19:23
 */
@Slf4j
public class Cache {

    //51
    static RemovalListener<String, RateLimiter> removalListener = (notification) -> {
        String uri = notification.getKey();
        log.info(uri + "被移除缓存");
    };

    //38
    static RemovalListener<String, RateLimiter> listener = RemovalListeners.asynchronous((notification) -> {

        String uri = notification.getKey();
        log.info(uri + "被移除缓存" + notification.getCause());

    }, Executors.newSingleThreadExecutor());

    /*static LoadingCache<String, RateLimiter> cache = CacheBuilder.newBuilder()
            .build(new CacheLoader<String, RateLimiter>() {

                @Override
                public RateLimiter load(String key) throws Exception {
                    return RateLimiter.create(10000);
                }
            });
*/

    static com.google.common.cache.Cache<String, RateLimiter> cache = CacheBuilder.newBuilder().build();

    public static void main(String[] args) throws ExecutionException {
        System.out.println(cache.size());
        System.out.println(cache.get("2", new Callable<RateLimiter>() {

            @Override
            public RateLimiter call() throws Exception {
                return RateLimiter.create(10000);
            }
        }));
        System.out.println(cache.size());
    }
}
